#ifndef ULTRASOUNDSENSOR_H
#define ULTRASOUNDSENSOR_H
#include "InterruptHandler.h"
#include "TimerEventQueue.h"

class UltrasoundSensor : public InterruptHandler, public TimerEventListener
{
public:
    UltrasoundSensor(int measPin, int trigPin, TimerQueue& timerp)
        :InterruptHandler(measPin), measurementPin(measPin),
        triggerPin(trigPin), timer(timerp), measurementReady(true)
    {
        pinMode(triggerPin, OUTPUT);
        pinMode(measurementPin, INPUT);
        digitalWrite(triggerPin, LOW);
    }
    virtual void onInterrupt()
    {
      if(!measurementReady)
        if(digitalRead(measurementPin) == HIGH)
            startMeasurement();
        else
            stopMeasurement();
    }
    void triggerMeasurement()
    {
        if(measurementReady)
        {
            measurementReady = false;
            digitalWrite(triggerPin, HIGH);
            //delayMicroseconds(10);
            //digitalWrite(triggerPin, LOW);
            timer.registerTimerEvent(this, 10);// 10us
//            Serial.println("Trigger");
        }

    }
    virtual long unsigned onTime()
    {

        digitalWrite(triggerPin, LOW);
  
        return 0;
    }
    bool isMeasurementReady()
    {
        return measurementReady;
    }
    long unsigned getMeasuredTime()
    {
        return measuredTime;
    }
private:
    void startMeasurement()
    {
        timestamp = micros();
    }
    void stopMeasurement()
    {
        measuredTime = micros() - timestamp;
        measurementReady = true;
    }
    volatile unsigned short measurementPin, triggerPin;
    volatile unsigned long timestamp, measuredTime;
    volatile bool measurementReady;
    TimerQueue& timer;

};

#endif // ULTRASOUNDSENSOR_H
